#pragma once

#include "U7FileDefs.h"
#include "Graphic.h"

inline PCOLORENTRY GetFilePalette( const char* paletteFile, int palIndex )
{
	PFLEXFILEHEADER pHeader = (PFLEXFILEHEADER)paletteFile;
	PFLEXFILEENTRY pEntry = &((PFLEXFILEENTRY)(pHeader+1))[palIndex];
	PCOLORENTRY pColors = (PCOLORENTRY)(paletteFile + pEntry->offset);
	return pColors;
}

inline void GetU7Palette( const char* paletteFile, int palIndex, RGBQUAD* rgb )
{
	PCOLORENTRY pColors = GetFilePalette(paletteFile,palIndex);

	for ( int i = 0; i < MAX_COLOR_ENTRIES; i++ )
	{
		rgb[i].rgbRed	= pColors[i].red   << 2;
		rgb[i].rgbGreen	= pColors[i].green << 2;
		rgb[i].rgbBlue	= pColors[i].blue  << 2;
	}
}

inline void SetGraphicPalette( const char* paletteFile, int palIndex, PGRAPHIC g )
{
	RGBQUAD rgb[256];
	PCOLORENTRY pColors = GetFilePalette(paletteFile,palIndex);

	for ( int i = 0; i < MAX_COLOR_ENTRIES; i++ )
	{
		rgb[i].rgbRed	= pColors[i].red   << 2;
		rgb[i].rgbGreen	= pColors[i].green << 2;
		rgb[i].rgbBlue	= pColors[i].blue  << 2;
	}

	SetColorTable( g, 0, 256, rgb );
}

inline void RotateGraphicPalette( PGRAPHIC g, int first, int num )
{
	RGBQUAD rgb[256];
	rgb[0] = g->bmInfo.bmiColors[first+num-1];
	memcpy( &rgb[1], &g->bmInfo.bmiColors[first], (num-1) * sizeof(RGBQUAD) );
	SetColorTable( g, first, num, rgb );
}

inline unsigned char FindColor( const RGBQUAD* rgb, unsigned char size, int r, int g, int b )
{
	unsigned char bestIndex = -1;
	unsigned bestDistance = 0x7FFFFFFF;

	for ( unsigned char i = 0; i < size; i++ )
	{
		int dr = r - rgb->rgbRed;
		int dg = g - rgb->rgbGreen;
		int db = b - rgb->rgbBlue;
		unsigned distance = dr * dr + dg * dg + db * db;
		if ( distance < bestDistance )
		{
			bestIndex = i;
			bestDistance = distance;
		}
		rgb++;
	}

	return bestIndex;
}
